import * as React from "react";
import { inject, observer } from "mobx-react";
import { Modal, message, Dropdown, Icon, Menu} from 'antd';
import { History, Location } from 'history';
import { ColumnProps } from 'antd/lib/table/interface';
import  PublicTable  from '../../../common/PublicTable';
import  HeaderButton  from '../../../common/header-button/HeaderButton';
import  EditModal  from '../../../common/editModal/EditModal';
import  CheckModal  from '../../../common/CheckModal';
import { getAuthObjectTreeSelect } from '../../../../util/util'
import { LoginStore, RoleStore, AuthObjectStore, AppStore} from '../../../../store';
import {
  pagedDatasAsync,
  upsertAsync,
  deleteAsync,
  batchDeleteAsync,
  batchUpsertAsync,
} from '../../../../basicData/api'
import '../../home.less';


interface IProps {
  history: History;
  location: Location;
  children?: AudioContextLatencyCategory;
  loginStore: LoginStore;
  roleStore: RoleStore;
  authObjectStore: AuthObjectStore;
  appStore: AppStore;
}


interface State {
  searchText: string;
  visible: boolean,
  isNew: boolean,
  value: any,
  isNewBind: boolean,
  bindVisible: boolean,
  bindValue: any,
  data: {
    totalCount: number,
    items: any
  }
  plainOptions: any,
  checkModalVisible: boolean,
}

//初始化state
const initialState: State = {
  searchText: '',
  visible: false,
  isNew: false,
  value: {},
  bindVisible: false,
  isNewBind: false,
  bindValue: {},
  data: {
    totalCount: 0,
    items: [],
  },
  plainOptions: [],
  checkModalVisible: false,
};

type IState = Readonly<typeof initialState>;

@inject("loginStore")
@inject("roleStore")
@inject("authObjectStore")
@inject("appStore")
@observer
class Roles extends React.Component<IProps, IState> {
  tableRef: any
  bindRef: any
  modalformRef: any
  type: string
  state: IState = initialState;

  UNSAFE_componentWillMount() {
    this.props.appStore.onSelectChange([], []);
    this.props.appStore.pageChange(1);
  }
  
  componentDidMount() {
    this.type = 'Role'
    this.getData({})
  }
  /**
   * 获取列表数据
   * @param type 接口名称
   * @param param 请求数据
   */
  getData = (param: any) => {
    pagedDatasAsync(this.type, param).then ((res: any) => {
      this.setState({
        data: res.result
      })
      
      this.props.roleStore.getRole(res.result.items)
    })
  }

  pageChange = (page: number) => {
    this.getData({
      skipCount: (page - 1) * 10,
    })
  }

  edit = (record: any) => {
    this.setState({
      isNew: false,
      visible: true,
      value: record
    })
  }

  delete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除角色：【 ${record.roleName} 】？` ,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        deleteAsync(this.type, record.id).then((res: any) => {
          if(res.success){
            message.success('删除成功')
            this.props.appStore.pageChange(1)
            this.getData({})
          }
        })
      },
    })  
  }

  deleteBindAuth = (value: any) => {
    batchDeleteAsync('AuthObjectRoleRelated', value).then((res: any) => {
      if (res.success) {
        message.success('删除角色权限关系成功')
        this.handleCancel();
        this.getData({})
      }
    })
  }

  openCheckModal = (record: any) => {
    // console.log(record)
    const { authObject } = record;
    const arr: any[] = [];
    authObject.map((item: any) => {
      // console.log(123,item, typeof(item.authRoleReleatedId))
      const obj = {
        value: item.authRoleReleatedId,
        label: item.objectName
      }
      arr.push(obj)
    })
    // console.log(arr)
    this.setState({
      plainOptions: arr,
      checkModalVisible: true,
    })   
  }

  saveFormRef = (formRef: any) => {
    this.modalformRef = formRef;
  }

  handleCancel = () => {
    this.setState({
      visible: false,
      checkModalVisible: false
    });
  }

  handleCancelBind = () => {
    this.setState({
      bindVisible: false,
    });
  }

  handleCreateBind = (values: any) => {
    const roleIdArr = values.roleRoleName
    const authObjecIdArr = values.authObjectObjectName
    let arr: any = [];
    roleIdArr.forEach((roleId: string) => {
      authObjecIdArr.forEach((authObject: any) => {
        const authObjectId = authObject.value
        arr.push({ entity: { roleId, authObjectId } })
      })
    })
    batchUpsertAsync('AuthObjectRoleRelated', arr).then((res: any) => {
      if(res.success) {
        message.success('编辑成功')
        this.setState({
          bindVisible: false
        })
        this.getData({})
      }
    })
  }

  bindAuth = (id: any) => {
    const { getAuthObjectTree, authObjectTree } = this.props.authObjectStore;
    this.setState({
      isNewBind: true,
      bindVisible: true,
      bindValue: {
        roleRoleName: [id],
      }
    });
    if(authObjectTree.length < 1) {
      getAuthObjectTree();
    }
  }

  handleCreate = (values: any) => {
    const { isNew } = this.state
    const { getAuthObjectTree, authObjectTree } = this.props.authObjectStore;

    upsertAsync(this.type, values).then((res: any) => {
      if(res.success){
        this.getData({})
        if(isNew) {
          this.setState({
            visible: false
          })
          Modal.confirm({
            title: '创建角色成功',
            content: '立即为角色绑定权限？',
            okText: '确定',
            cancelText: '暂不绑定',
            onOk: () => this.bindAuth(res.result)
          })
        } else {
          message.success('修改成功')
          this.setState({
            visible: false
          })
        }
      }
    })
  }

  authObjectChange = (data: any) => {
    const arr: string[] = [];
    data.map((item: any) => {
      arr.push(item.objectName)
    })
    return arr.join('，')
  }

  render() {
    const { visible, isNew, value, data, isNewBind, bindVisible, bindValue, plainOptions, checkModalVisible  } = this.state
    const { allRole } = this.props.roleStore;
    const { getAuthObjectTree, authObjectTree } = this.props.authObjectStore;
    const { selectedRowIds, } = this.props.appStore
    const authObjectTreeSelect = getAuthObjectTreeSelect(authObjectTree)

    const more =(record: any) =>  (
      <Menu>
        <Menu.Item key="bind" onClick={() => this.bindAuth(record.id)} >分配权限</Menu.Item>
        <Menu.Item key="cancel" onClick={() => this.openCheckModal(record)}>解除权限</Menu.Item>
      </Menu>
    );

    const columns: ColumnProps<Roles.IRoles>[] = [
      {
        title: '序号',
        key: "index",
        width: 68,
        render: (text, record, index) => {
          return (<div>{index + 1}</div>)
        }
      },
      {
      title: '角色编码',
      width: 128,
      dataIndex: 'roleCode',
      key: 'roleCode',
    },
    {
      title: '角色名称',
      width: 128,
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '权限',
      key: "authObject",
      render: (text, record: any, index) => {
        return (<div>{record.authObject.length > 0
          ? this.authObjectChange(record.authObject): '--'}</div>)
      }
    },
    {
      title: '操作',
      width: 120,
      key: 'operation',
      render: (text, record) => {
        return (
          <div>
            <a onClick={() => this.edit(record)}>编辑   </a>
            {/* <a onClick={() => this.delete(record)}> 删除</a> */}
            <a>
              <Dropdown overlay={more(record)} placement="bottomLeft">
                <span>更多<Icon type="down" /></span>
              </Dropdown>
            </a>
          </div>
        )
      }
    }]

    const buttonConfig = {
      content: {
        isUpsert: true,
        isSearch: true,
        isDelete: true,
        isBind: false,
      },
      columns,
      searchConfig: [
        { type: 'input', name: '角色编码', key: 'roleCode', },
        { type: 'input', name: '角色名称', key: 'roleName',}
      ],
      plus: () => {
        this.setState({
          isNew: true,
          visible: true,
          value: {}
        })
      },
      sort: (value: any) => {this.getData({sorting: value})},
      search: (filter: any)=> {this.getData({filter:{andFilter: filter}})},
      reset: () => {this.getData({})},
      bind: () => {
        this.setState({
          isNewBind: true,
          bindVisible: true,
          bindValue: {
            roleRoleName: [...selectedRowIds],
          }
        });
        if(authObjectTree.length < 1) {
          getAuthObjectTree();
        }
      }, 
      batchDelete: () => {
        batchDeleteAsync(this.type, selectedRowIds)
        .then((res: any) => {
          if(res.success){
            this.props.appStore.pageChange(1)
            message.success('删除成功')
            this.getData({})
          }
        })
        
      },
    }
    const roleAdd = [
      { 
        type: 'input',
        name: '角色编码',
        key: 'roleCode',
        rule: { required: true, message: '请输入编码' }
      },
      { 
        type: 'input',
        name: '角色名称',
        key: 'roleName',
        rule: { required: true, message: '请输入名称' }
      },
    ]

    const bindConfig = [
      { 
        type: 'select_multi',
        name: '角色',
        key: 'roleRoleName',
        options: allRole || [],
        rule: { required: true, message: '请选择'  }
      },
      { 
        type: 'select_tree',
        name: '权限',
        key: 'authObjectObjectName',
        options: authObjectTreeSelect || [],
        rule: { required: true, message: '请选择'  }
      },
    ]


    return (
      <div>
        <HeaderButton
          {...buttonConfig}
        />
        <PublicTable
          columns={columns}
          dataSource={data}
          ref={ref => this.tableRef = ref}
          pageChange={this.pageChange}
        />
        <EditModal
          title={isNew ? '新增角色' : '编辑角色'}
          isNew={isNew}
          values={value}
          wrappedComponentRef={this.saveFormRef}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          editconfig={roleAdd}
        />
        <EditModal
          title={isNewBind ? '新增角色权限关系' : '编辑角色权限关系'}
          isNew={isNewBind}
          values={bindValue}
          ref={ref => this.bindRef = ref}
          visible={bindVisible}
          onCancel={this.handleCancelBind}
          onCreate={this.handleCreateBind}
          editconfig={bindConfig}
        />
        <CheckModal
          plainOptions={plainOptions}
          visible={checkModalVisible}
          title={'请勾选需要删除的权限'}
          onCancel={this.handleCancel}
          onCreate={this.deleteBindAuth}
        />
      </div>
      )
  }
}

export default Roles
